var usersModel = require("../models/users");
var fs = require("fs");
var mongoose = require("mongoose");
const config = require("../utils/aliconfig");
const Core = require("@alicloud/pop-core");
let client = new Core(config.alicloud);
var {
  remove,
  findOneByid,
  updateOne,
  createOne,
  find,
  count,
} = require("../dao/base.js");
var videosModel = require("../models/videos");
var commentsModel = require("../models/comments");
var messagesModel = require("../models/messages");
const dayjs = require("dayjs");
const Token = require("../modules/Token");

module.exports.register = async function (req, res, next) {
  var data = {
    userid: req.body.userid,
    password: req.body.password,
  };
  var doc = await findOneByid(usersModel, {
    userid: data.userid,
    isEffective: true,
  });
  if (doc != null) {
    res.sendResult(null, 403, "用户已存在！");
  } else {
    var doc2 = await createOne(usersModel, data);
    res.sendResult(doc2, 201, "用户创建成功！");
  }
};

module.exports.useridLogin = async (req, res, next) => {
  var userInfo = {
    userid: req.body.userid,
    password: req.body.password,
    isEffective: true,
  };
  var doc = await find(usersModel, userInfo);
  if (doc.length > 0) {
    let secretOrPrivateKey = "This is perfect projects.";
    var token = Token.encrypt(userInfo, secretOrPrivateKey, 60 * 60 * 24 * 7); //一周过期
    token = "bearer " + token;
    return res.sendResult(
      { userid: userInfo.userid, token,name:doc[0].name},
      200,
      "登录成功！"
    );
  } else {
    return res.sendResult(null, 403, "登录失败！");
  }
};

//手机号码验证
var validatePhoneCode = [];
//验证手机号和验证码是否相等
let findCodeAndPhone = (phone, code) => {
  for (var item of validatePhoneCode) {
    if (phone == item.phone && code == item.code) {
      return "login";
    }
  }
  return false;
};

module.exports.codePhoneLogin = (req, res, next) => {
  let { phone, code } = req.query;
  //验证手机号是否发送过验证码
  if (sendCodeP(phone)) {
    let status = findCodeAndPhone(phone, code);
    if (status == "login") {
      //已经登录成功
      //登录成功之后的操作
      // let user = await phoneLoginBind(phone);
      res.send({
        code: 200,
        msg: "登录已成功",
        // data: user[0]
      });
    } else if (status == "error") {
      res.send({
        code: 200,
        msg: "登录失败",
      });
    }
  } else {
    res.send({
      code: 400,
      msg: "未发送验证码",
    });
  }
};

module.exports.sendCoreCode = (req, res, next) => {
  let phone = req.body.phone;
  let code = rand(1000, 7777);
  var params = {
    // "RegionId": "cn-hangzhou",
    PhoneNumbers: phone,
    SignName: "asdjminq",
    TemplateCode: "SMS_153055065",
    TemplateParam: JSON.stringify({ code: code }),
  };
  client.request("SendSms", params, requestOption).then((result) => {
    if (result.Code == "OK") {
      res.send({
        code: 200,
        msg: "发送成功",
      });
      validatePhoneCode.push({
        phone: phone,
        code: code,
      });
    } else {
      res.send({
        code: 400,
        msg: "发送失败",
      });
    }
  });
};

//更新用户基本信息
module.exports.updateUser = async (req, res, next) => {
  var userid = req.params.userid;
  var userInfo = req.body;
  if (userInfo) {
    var result = await updateOne(usersModel, { userid }, { ...userInfo });
    res.sendResult(result, 200, "更新成功！");
  }
};
//获取用户基本信息
module.exports.getUserInfo = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var userid = req.params.userid;
  if (loginUserid === undefined) {
    if (userid) {
      var result = await findOneByid(usersModel, { userid, isEffective: true });
      res.sendResult({ ...result._doc, is_followed: false }, 200, "查看成功");
    }
  } else {
    var loginUserFollow = await find(
      usersModel,
      { userid: loginUserid, isEffective: true },
      "follow"
    );
    if (userid) {
      var index = loginUserFollow[0].follow.findIndex((v) => userid == v) + 1;
      var result = await findOneByid(usersModel, { userid, isEffective: true });
      res.sendResult(
        { ...result._doc, is_followed: index ? true : false },
        200,
        "查看成功"
      );
    }
  }
};

//添加用户一个关注
module.exports.addUserFollow = async (req, res) => {
  let userid = req.params.userid;
  let follow = req.body.userid;
  if (userid) {
    var result1 = await updateOne(
      usersModel,
      { userid },
      { $addToSet: { follow: follow } }
    );
    var result2 = await updateOne(
      usersModel,
      { userid: follow },
      { $addToSet: { fans: userid } }
    );
    return res.sendResult(result1, 200, `${userid}用户关注了${follow}`);
  }
  res.sendResult(null, 403, "没有用户");
};
//用户发布了一个视频
module.exports.addUserVideo = async (req, res) => {
  let userid = req.params.userid;
  const files = req.files;
  let publictime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  if (userid) {
    var video = files[0];
    fs.renameSync(video.path, video.path + ".mp4");
    var poster = files[1];
    fs.renameSync(poster.path, poster.path + ".png");
    let introduce = req.body.introduce;
    let position = req.body.position;
    let choosenVideoLabel = req.body.choosenVideoLabel.split(",");
    var data = {
      src: "/" + video.path + ".mp4",
      userid,
      position,
      choosenVideoLabel,
      introduce,
      publictime,
      poster: "/" + poster.path + ".png",
    };
    // 上传视频newFocuVideos
    var doc = await createOne(videosModel, data);
    if (doc != null) {
      //添加到用户
      var docs2 = await updateOne(
        usersModel,
        { userid: data.userid },
        { $addToSet: { myvideos: doc._id } }
      );
      var result = await findOneByid(
        usersModel,
        { userid, isEffective: true },
        "fans"
      );
      var result2 = await find(usersModel, {
        userid: { $in: result.fans },
        isEffective: true,
      });
      for (let i = 0; i < result2.length; i++) {
        var addNewUser = await find(usersModel, {
          userid: result2[i].userid,
          isEffective: true,
        });
        var docs3 = await updateOne(
          usersModel,
          { userid: result2[i].userid },
          { newFocuVideos: ++addNewUser[0].newFocuVideos }
        );
      }
    }
  }
  res.sendResult(req.files, 200, `${userid}发布了视频`);
};
//用户把视频加入了喜欢
module.exports.addUserlikeVideo = async (req, res) => {
  let userid = req.params.userid;
  let likevideos = req.body.videoid;
  if (userid) {
    var result = await updateOne(
      usersModel,
      { userid },
      { $addToSet: { likevideos } }
    );
    if (result.nModified !== 0) {
      var result2 = await find(
        videosModel,
        { _id: likevideos, isEffective: true },
        "likeNum"
      );
      var result3 = await updateOne(
        videosModel,
        { _id: likevideos },
        { likeNum: ++result2[0].likeNum }
      );
      return res.sendResult(
        result,
        200,
        `${userid}加入了一个喜欢:${likevideos}`
      );
    }
    res.sendResult(result, 403, `${userid}已经加入喜欢了:${likevideos}`);
  }
};
//用户取消了关注
module.exports.removeUserFollow = async (req, res) => {
  let userid = req.params.userid;
  let follow = req.body.userid;
  if (userid) {
    var result = await updateOne(usersModel, { userid }, { $pull: { follow } });
    var result = await updateOne(
      usersModel,
      { userid: follow },
      { $pull: { fans: userid } }
    );
  }
  res.sendResult(result, 200, `${userid}用户取消了关注:${follow}`);
};
//用户取消了喜欢
module.exports.removeUserLikeVideo = async (req, res) => {
  let userid = req.params.userid;
  let likevideos = req.body.videoid;
  if (userid) {
    var result = await updateOne(
      usersModel,
      { userid },
      { $pull: { likevideos } }
    );
  }
  if (result.nModified !== 0) {
    var result2 = await find(
      videosModel,
      { _id: likevideos, isEffective: true },
      "likeNum"
    );
    var result3 = await updateOne(
      videosModel,
      { _id: likevideos },
      { likeNum: --result2[0].likeNum }
    );
    return res.sendResult(result, 200, `${userid}用户取消了喜欢:${likevideos}`);
  }
  res.sendResult(result, 403, `${userid}用户已经取消了:${likevideos}`);
};

//用户删除了自己发布的视频
module.exports.removeUserSelfVideo = async (req, res) => {
  let userid = req.params.userid;
  let myvideos = req.body.videoid;
  if (userid) {
    var result = await updateOne(
      usersModel,
      { userid },
      { $pull: { myvideos: mongoose.Types.ObjectId(myvideos) } }
    );
    var result3 = await remove(videosModel, { _id: myvideos });
  }
  res.sendResult(result3, 200, `${userid}用户删除了视频:${myvideos}`);
};

//获取某个用户喜欢的视频
module.exports.getUserLikeVideo = async (req, res) => {
  let userid = req.params.userid;
  if (userid) {
    var result = await findOneByid(
      usersModel,
      { userid, isEffective: true },
      "likevideos"
    );
  }
  var result2 = await find(videosModel, {
    _id: { $in: result.likevideos },
    isEffective: true,
  });
  res.sendResult(result2, 200, `获取到${userid}用户的喜欢`);
};

//获取某个用户自己的视频
module.exports.getUserSelfVideo = async (req, res) => {
  let userid = req.params.userid;
  let videoType = req.query.videoType;
  let loginUserid = req.query.loginUserid;
  var page = req.query.page || 1;
  let singeVideoId = req.query.singeVideoId;

  var data = {
    total: 0,
    curPage: page,
    list: [],
    pageSize: 7,
  };
  var result, result2;
  if (loginUserid === undefined) {
    if (userid) {
      if (videoType == 0) {
        result = await findOneByid(
          usersModel,
          { userid, isEffective: true },
          "myvideos"
        );
        result2 = await find(
          videosModel,
          { _id: { $in: result.myvideos }, isEffective: true },
          null,
          {
            skip: (page - 1) * data.pageSize,
            limit: data.pageSize,
            sort: { _id: -1 },
          }
        );
      } else if (videoType == 1) {
        result = await findOneByid(
          usersModel,
          { userid, isEffective: true },
          "likevideos"
        );
        result2 = await find(
          videosModel,
          { _id: { $in: result.likevideos }, isEffective: true },
          null,
          {
            skip: (page - 1) * data.pageSize,
            limit: data.pageSize,
            sort: { _id: -1 },
          }
        );
      } else if (videoType == 2) {
        result = await findOneByid(
          usersModel,
          { userid, isEffective: true },
          "likevideos"
        );
        result2 = await find(videosModel, { _id: page, isEffective: true });
      }
      //查找登录用户喜欢的video数组
      var video = new Array();
      for (let i = 0; i < result2.length; i++) {
        //查找视频作者的信息
        const res = await find(
          usersModel,
          { userid: result2[i].userid, isEffective: true },
          ["photo", "name", "likevideos"]
        );
        //查找登录用户喜欢的列表是否等于这个视频
        result2[i].photo = res[0].photo;
        result2[i].name = res[0].name;
        video.push({
          ...result2[i]._doc,
          name: res[0].name,
          photo: res[0].photo,
          isLike: false,
          isFollow: false,
        });
      }
      res.sendResult(video, 200, `获取到${userid}用户的视频`);
    } else {
      res.sendResult(video, 403, `没有用户id`);
    }
  } else {
    if (userid) {
      if (videoType == 0) {
        result = await findOneByid(
          usersModel,
          { userid, isEffective: true },
          "myvideos"
        );
        result2 = await find(
          videosModel,
          { _id: { $in: result.myvideos }, isEffective: true },
          null,
          {
            skip: (page - 1) * data.pageSize,
            limit: data.pageSize,
            sort: { _id: -1 },
          }
        );
      } else if (videoType == 1) {
        result = await findOneByid(
          usersModel,
          { userid, isEffective: true },
          "likevideos"
        );
        result2 = await find(
          videosModel,
          { _id: { $in: result.likevideos }, isEffective: true },
          null,
          {
            skip: (page - 1) * data.pageSize,
            limit: data.pageSize,
            sort: { _id: -1 },
          }
        );
      } else if (videoType == 2) {
        result = await findOneByid(
          usersModel,
          { userid, isEffective: true },
          "likevideos"
        );
        result2 = await find(videosModel, { _id: page, isEffective: true });
      }
      //查找登录用户喜欢的video数组
      var loginUserLoveVideo = await find(
        usersModel,
        { userid: loginUserid, isEffective: true },
        ["likevideos", "follow"]
      );
      var video = new Array();
      for (let i = 0; i < result2.length; i++) {
        //查找视频作者的信息
        const res = await find(
          usersModel,
          { userid: result2[i].userid, isEffective: true },
          ["photo", "name", "likevideos"]
        );
        //查找登录用户喜欢的列表是否等于这个视频
        var index =
          loginUserLoveVideo[0].likevideos.findIndex(
            (v) => result2[i]._id == v
          ) + 1;
        var index2 =
          loginUserLoveVideo[0].follow.findIndex(
            (v) => result2[i].userid == v
          ) + 1;

        result2[i].photo = res[0].photo;
        result2[i].name = res[0].name;
        video.push({
          ...result2[i]._doc,
          name: res[0].name,
          photo: res[0].photo,
          isLike: index ? true : false,
          isFollow: index2 ? true : false,
        });
      }
      res.sendResult(video, 200, `获取到${userid}用户的视频`);
    } else {
      res.sendResult(video, 403, `没有用户id`);
    }
  }
};

//获取用户粉丝列表
module.exports.getUserFans = async (req, res) => {
  var page = req.query.page || 1;
  let loginUserid = req.query.loginUserid;

  var data = {
    total: 0,
    curPage: page,
    list: [],
    pageSize: 10,
  };
  let userid = req.params.userid;
  if (loginUserid === undefined) {
    if (userid) {
      var result = await findOneByid(
        usersModel,
        { userid, isEffective: true },
        "fans",
        {
          skip: (page - 1) * data.pageSize,
          limit: data.pageSize,
          sort: { _id: -1 },
        }
      );
      var follow = new Array();
      var result2 = await find(
        usersModel,
        { userid: { $in: result.fans }, isEffective: true },
        null,
        {
          skip: (page - 1) * data.pageSize,
          limit: data.pageSize,
          sort: { _id: -1 },
        }
      );

      for (let i = 0; i < result2.length; i++) {
        follow.push({ ...result2[i]._doc, is_followed: false });
      }
      res.sendResult(follow, 200, result.fans.length);
    }
  } else {
    var loginUserFollow = await find(
      usersModel,
      { userid: loginUserid, isEffective: true },
      "follow"
    );
    if (userid) {
      var result = await findOneByid(
        usersModel,
        { userid, isEffective: true },
        "fans",
        {
          skip: (page - 1) * data.pageSize,
          limit: data.pageSize,
          sort: { _id: -1 },
        }
      );
      var follow = new Array();
      var result2 = await find(
        usersModel,
        { userid: { $in: result.fans }, isEffective: true },
        null,
        {
          skip: (page - 1) * data.pageSize,
          limit: data.pageSize,
          sort: { _id: -1 },
        }
      );

      for (let i = 0; i < result2.length; i++) {
        var index =
          loginUserFollow[0].follow.findIndex((v) => result2[i].userid == v) +
          1;
        follow.push({ ...result2[i]._doc, is_followed: index ? true : false });
      }
      res.sendResult(follow, 200, result.fans.length);
    }
  }
};

//获取用户的关注列表
module.exports.getUserFollow = async (req, res) => {
  var page = req.query.page || 1;
  let loginUserid = req.query.loginUserid;
  let userid = req.params.userid;
  var data = {
    total: 0,
    curPage: page,
    list: [],
    pageSize: 10,
  };
  if (loginUserid === undefined) {
    var follow = new Array();
    if (userid) {
      var result = await findOneByid(
        usersModel,
        { userid, isEffective: true },
        "follow"
      );
      var result2 = await find(
        usersModel,
        { userid: { $in: result.follow }, isEffective: true },
        null,
        {
          skip: (page - 1) * data.pageSize,
          limit: data.pageSize,
          sort: { _id: -1 },
        }
      );
      for (let i = 0; i < result2.length; i++) {
        follow.push({ ...result2[i]._doc, is_followed: false });
      }
      res.sendResult(follow, 200, result.follow.length);
    }
  } else {
    var loginUserFollow = await find(
      usersModel,
      { userid: loginUserid, isEffective: true },
      "follow"
    );
    var follow = new Array();
    if (userid) {
      var result = await findOneByid(
        usersModel,
        {
          userid,
          isEffective: true,
        },
        "follow"
      );
      var result2 = await find(
        usersModel,
        { userid: { $in: result.follow }, isEffective: true },
        null,
        {
          skip: (page - 1) * data.pageSize,
          limit: data.pageSize,
          sort: { _id: -1 },
        }
      );
      for (let i = 0; i < result2.length; i++) {
        var index =
          loginUserFollow[0].follow.findIndex((v) => result2[i].userid == v) +
          1;
        follow.push({ ...result2[i]._doc, is_followed: index ? true : false });
      }
      res.sendResult(follow, 200, result.follow.length);
    }
  }
};

//用户更改头像
module.exports.updateUserPhoto = async (req, res) => {
  let userid = req.params.userid;
  const file = req.file;
  if (userid) {
    fs.renameSync(file.path, file.path + ".png");
    //添加到用户
    var docs2 = await updateOne(
      usersModel,
      { userid, isEffective: true },
      { photo: "/" + file.path + ".png" }
    );
  }
  res.sendResult(docs2, 200, `${userid}上传了图片`);
};

//更新用户的喜欢
module.exports.updateUserLikeStyle = async (req, res) => {
  let userid = req.params.userid;
  const likeVideoStyle = req.body.likeVideoStyle;
  if (userid) {
    //添加到用户
    var docs2 = await updateOne(
      usersModel,
      { userid, isEffective: true },
      { likeVideoStyle }
    );
  }
  res.sendResult(docs2, 200, `${userid}更新了喜欢类型`);
};

////更新用户基本资料
module.exports.updateUserInfo = async (req, res) => {
  let userid = req.params.userid;
  let userInfo = req.body;

  if (userid) {
    var docs2 = await updateOne(
      usersModel,
      { userid, isEffective: true },
      userInfo
    );
  }
  res.sendResult(docs2, 200, `${userid}上传了图片`);
};

//创建了一条评论
module.exports.createComment = async (req, res) => {
  let publictime = dayjs().format("YYYY-MM-DD HH:mm");
  let userid = req.params.userid;
  let videoid = req.body.videoid;
  let commentid = req.body.commentid;
  let content = req.body.content;
  let replyUser = req.body.replyUser;
  let comment;
  if (userid && videoid) {
    comment = await createOne(commentsModel, {
      userid,
      videoid,
      content,
      publictime,
    });
    var result = await updateOne(
      videosModel,
      { _id: videoid },
      { $addToSet: { comments: comment._id } }
    );
  } else if (userid && commentid) {
    comment = await createOne(commentsModel, {
      userid,
      commentid,
      content,
      publictime,
    });
    var result = await updateOne(
      commentsModel,
      { _id: commentid },
      { $addToSet: { childComment: comment._id } }
    );
  }
  res.sendResult(comment, 200, `${userid}对视频${videoid}发表了评论`);
};

////更新用户基本资料
module.exports.updateUserInfo = async (req, res) => {
  let userid = req.params.userid;
  let userInfo = req.body;

  if (userid) {
    var docs2 = await updateOne(usersModel, { userid }, userInfo);
  }
  res.sendResult(docs2, 200, `${userid}上传了图片`);
};

////用户点赞了一条评论
module.exports.onLikeComment = async (req, res) => {
  let userid = req.params.userid;
  let commentid = req.body.commentid;
  if (commentid) {
    var result = await updateOne(
      usersModel,
      { userid },
      { $addToSet: { likeComments: commentid } }
    );
    if (result.nModified !== 0) {
      //获取点赞数
      var result2 = await find(commentsModel, { _id: commentid }, "likeNum");
      //点赞数加一
      var result3 = await updateOne(
        commentsModel,
        { _id: commentid },
        { likeNum: ++result2[0].likeNum }
      );
      return res.sendResult(
        result,
        200,
        `${userid}加入了一个喜欢:${commentid}`
      );
    }
    res.sendResult(result, 403, `${userid}已经加入喜欢了`);
  }
};
//用户取消了点赞评论
module.exports.removeUserLikeComment = async (req, res) => {
  let userid = req.params.userid;
  let commentid = req.body.commentid;
  if (commentid) {
    var result = await updateOne(
      usersModel,
      { userid },
      { $pull: { likeComments: commentid } }
    );
  }
  if (result.nModified !== 0) {
    var result2 = await find(commentsModel, { _id: commentid }, "likeNum");
    var result3 = await updateOne(
      commentsModel,
      { _id: commentid },
      { likeNum: --result2[0].likeNum }
    );
    return res.sendResult(result, 200, `${userid}用户取消了喜欢:${commentid}`);
  }
  res.sendResult(result, 403, `${userid}用户已经取消了:${commentid}`);
};

//用户删除了评论
module.exports.removeUserComment = async (req, res) => {
  let userid = req.params.userid;
  let videoid = req.body.videoid;
  let commentid = req.body.commentid;
  let removeCommentid = req.body.removeCommentid;

  if (userid && videoid && removeCommentid) {
    var result1 = await updateOne(
      videosModel,
      { _id: videoid },
      { $pull: { comments: mongoose.Types.ObjectId(removeCommentid) } }
    );
    //     var result1 = await updateOne(usersModel,{userid:'user1'},
    // { $pull: { fans:'xinkai' } })

    comment = await remove(commentsModel, { _id: removeCommentid });
  } else if (userid && commentid && removeCommentid) {
    var result2 = await updateOne(
      commentsModel,
      { _id: commentid },
      { $pull: { childComment: mongoose.Types.ObjectId(removeCommentid) } }
    );
    comment = await remove(commentsModel, { _id: removeCommentid });
  }
  res.sendResult(comment, 200, `${userid}删除了评论`);
};

//获取某个用户自己的视频
module.exports.getRecommentVideo = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var page = req.query.page || 1;

  var result2;
  var videoRecommend = new Array();
  if (loginUserid === undefined) {
    for (let i = 0; i < 7; i++) {
      const total1 = await count(videosModel, {}, null);
      result2 = await find(videosModel, { isEffective: true }, null, {
        skip: Math.ceil(Math.random() * total1),
        limit: 1,
      });
      videoRecommend.push(result2[0]);
    }
    //查找登录用户喜欢的video数组
    var video = new Array();
    for (let i = 0; i < videoRecommend.length; i++) {
      //查找视频作者的信息
      const res = await find(
        usersModel,
        { userid: videoRecommend[i].userid, isEffective: true },
        ["photo", "name", "likevideos"]
      );
      //查找登录用户喜欢的列表是否等于这个视频
      videoRecommend[i].photo = res[0].photo;
      videoRecommend[i].name = res[0].name;
      video.push({
        ...videoRecommend[i]._doc,
        name: res[0].name,
        photo: res[0].photo,
        isLike: false,
        isFollow: false,
      });
    }
    res.sendResult(video, 200, `获取到${loginUserid}用户的视频`);
  } else {
    var likeVideoStyle = await find(
      usersModel,
      { userid: loginUserid, isEffective: true },
      "likeVideoStyle"
    );
    likeVideoStyle = likeVideoStyle[0].likeVideoStyle;
    for (let i = 0; i < 7; i++) {
      const total2 = await count(
        videosModel,
        { choosenVideoLabel: { $elemMatch: { $in: likeVideoStyle } } },
        null
      );
      result2 = await find(
        videosModel,
        {
          choosenVideoLabel: { $elemMatch: { $in: likeVideoStyle } },
          isEffective: true,
        },
        null,
        { skip: Math.ceil(Math.random() * total2), limit: 1 }
      );
      videoRecommend.push(result2[0]);
    }
    //查找登录用户喜欢的video数组
    var loginUserLoveVideo = await find(
      usersModel,
      { userid: loginUserid, isEffective: true },
      ["likevideos", "follow"]
    );
    var video = new Array();
    for (let i = 0; i < videoRecommend.length; i++) {
      //查找视频作者的信息
      const res = await find(
        usersModel,
        { userid: videoRecommend[i].userid, isEffective: true },
        ["photo", "name", "likevideos"]
      );
      //查找登录用户喜欢的列表是否等于这个视频
      var index =
        loginUserLoveVideo[0].likevideos.findIndex(
          (v) => videoRecommend[i]._id == v
        ) + 1;
      var index2 =
        loginUserLoveVideo[0].follow.findIndex(
          (v) => videoRecommend[i].userid == v
        ) + 1;
      videoRecommend[i].photo = res[0].photo;
      videoRecommend[i].name = res[0].name;
      video.push({
        ...videoRecommend[i]._doc,
        name: res[0].name,
        photo: res[0].photo,
        isLike: index ? true : false,
        isFollow: index2 ? true : false,
      });
    }
    res.sendResult(video, 200, `获取到${loginUserid}用户的视频`);
  }
};

//获取某个用户自己的视频
module.exports.getUserFocusVideo = async (req, res) => {
  let loginUserid = req.query.loginUserid;
  var page = req.query.page || 1;
  var data = {
    curPage: page,
    pageSize: 7,
  };
  var result2;
  var loginUser = await find(
    usersModel,
    { userid: loginUserid, isEffective: true },
    ["likevideos", "follow"]
  );
  var docs3 = await updateOne(
    usersModel,
    { userid: loginUserid },
    { newFocuVideos: 0 }
  );
  follow = loginUser[0].follow;
  result2 = await find(
    videosModel,
    { userid: { $in: follow }, isEffective: true },
    null,
    {
      skip: (page - 1) * data.pageSize,
      limit: data.pageSize,
      sort: { _id: -1 },
    }
  );
  //查找登录用户喜欢的video数组
  var video = new Array();
  for (let i = 0; i < result2.length; i++) {
    //查找视频作者的信息
    const res = await find(
      usersModel,
      { userid: result2[i].userid, isEffective: true },
      ["photo", "name", "likevideos"]
    );
    if (res[0] === undefined) continue;
    //查找登录用户喜欢的列表是否等于这个视频
    var index =
      loginUser[0].likevideos.findIndex((v) => result2[i]._id == v) + 1;
    var index2 =
      loginUser[0].follow.findIndex((v) => result2[i].userid == v) + 1;
    video.push({
      ...result2[i]._doc,
      name: res[0].name,
      photo: res[0].photo,
      isLike: index ? true : false,
      isFollow: index2 ? true : false,
    });
  }
  res.sendResult(video, 200, `获取到${loginUserid}用户的视频`);
};

//用户发起了一条消息
module.exports.createMessage = async (req, res) => {
  let publictime = dayjs().format("YYYY-MM-DD HH:mm");
  let userid = req.params.userid;
  let chatUserid = req.body.chatUserid;
  let content = { content: req.body.content, publictime, userid: userid };
  let comment;
  var doc = await find(messagesModel, {
    userid: userid,
    chatUserid: chatUserid,
  });
  if (doc.length === 0) {
    comment = await createOne(messagesModel, { userid, chatUserid, content });
  } else {
    var message = await updateOne(
      messagesModel,
      { userid, chatUserid },
      { $push: { content: content } }
    );
  }

  var doc2 = await find(messagesModel, {
    userid: chatUserid,
    chatUserid: userid,
  });
  if (doc2.length === 0) {
    comment = await createOne(messagesModel, {
      userid: chatUserid,
      chatUserid: userid,
      content,
      isNewMessage: 1,
    });
  } else {
    var message = await updateOne(
      messagesModel,
      { userid: chatUserid, chatUserid: userid },
      { $push: { content: content } }
    );
    var findMessage = await find(messagesModel, {
      userid: chatUserid,
      chatUserid: userid,
    });
    var message = await updateOne(
      messagesModel,
      { userid: chatUserid, chatUserid: userid },
      { isNewMessage: ++findMessage[0].isNewMessage }
    );
  }
  res.sendResult(message, 200, `${userid}对视频${chatUserid}发表了评论`);
};

//获取用户的消息
module.exports.getUserMessage = async (req, res) => {
  let userid = req.params.userid;
  var doc = await find(messagesModel, { userid: userid });
  var messages = new Array();
  //将userid转化为请求人

  for (let i = 0; i < doc.length; i++) {
    var user = await find(
      usersModel,
      { userid: doc[i].chatUserid, isEffective: true },
      ["name", "photo", "baseUrl"]
    );
    messages.push({
      ...doc[i]._doc,
      chatName: user[0].name,
      chatPhoto: user[0].photo,
      baseUrl: user[0].baseUrl,
    });
  }
  var selfInfo = await find(usersModel, { userid, isEffective: true }, [
    "name",
    "photo",
    "baseUrl",
  ]);
  res.sendResult({ messages, selfInfo }, 200, doc.length);
};

//获取删除消息
module.exports.removeUserMessage = async (req, res) => {
  let userid = req.params.userid;
  let chatUserid = req.body.chatUserid;
  var doc = await remove(messagesModel, {
    userid: userid,
    chatUserid: chatUserid,
  });
  res.sendResult(doc, 200, `${userid}的删除了对的${chatUserid}消息`);
};

//获取对话消息
module.exports.getOneMessage = async (req, res) => {
  let chatUserid = req.query.chatUserid;
  let userid = req.params.userid;
  var doc = await find(messagesModel, {
    userid: userid,
    chatUserid: chatUserid,
  });
  // 请求过置为false
  await updateOne(
    messagesModel,
    { userid: userid, chatUserid: chatUserid },
    { isNewMessage: 0 }
  );

  //将userid转化为请求人
  if (doc.length === 0) {
    var user = await find(
      usersModel,
      { userid: chatUserid, isEffective: true },
      ["name", "photo", "baseUrl"]
    );
    let messages = {
      chatUserid: chatUserid,
      chatName: user[0].name,
      chatPhoto: user[0].photo,
      baseUrl: user[0].baseUrl,
    };
    var selfInfo = await find(usersModel, { userid, isEffective: true }, [
      "name",
      "photo",
      "baseUrl",
    ]);
    return res.sendResult({ messages, selfInfo }, 200, doc.length);
  }

  var user = await find(
    usersModel,
    { userid: doc[0].chatUserid, isEffective: true },
    ["name", "photo", "baseUrl"]
  );
  let messages = {
    ...doc[0]._doc,
    chatName: user[0].name,
    chatPhoto: user[0].photo,
    baseUrl: user[0].baseUrl,
  };
  var selfInfo = await find(usersModel, { userid, isEffective: true }, [
    "name",
    "photo",
    "baseUrl",
  ]);
  res.sendResult({ messages, selfInfo }, 200, doc.length);
};
